package com.yycx.module.bus.provider.handler.haiying;

import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.constants.CommonConstants;
import com.yycx.common.utils.ApiAssert;
import com.yycx.groovy.provider.script.MyGroovyScriptEngine;
import com.yycx.module.bus.client.entity.*;
import com.yycx.module.bus.client.entity.hy.BusPolicyDept;
import com.yycx.module.bus.client.entity.hy.BusPolicyDrug;
import com.yycx.module.bus.client.entity.hy.HyOrder;
import com.yycx.module.bus.client.entity.hy.HyOrderDetail;
import com.yycx.module.bus.client.enums.DeptTypeEnum;
import com.yycx.module.bus.client.enums.HySaleTypeEnum;
import com.yycx.module.bus.client.enums.SendTypeEnum;
import com.yycx.module.bus.provider.service.*;
import com.yycx.module.bus.provider.service.hy.*;
import com.yycx.module.bus.provider.strategy.SettleStrategyContext;
import com.yycx.module.user.client.entity.AppPosition;
import com.yycx.module.user.provider.service.AppPositionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zyf
 */
@Component
@Slf4j
public class HyOrderUtils {

    @Autowired
    private MyGroovyScriptEngine groovyScriptEngine;

    @Resource
    private BusPolicyDrugService policyDrugService;

    @Resource
    private BusDeptService deptService;

    @Resource
    private BusPolicyDeptService policyDeptService;

    @Resource
    private BusDrugsService drugsService;

    @Resource
    private BusSalemanService saleManService;

    @Resource
    private BusPolicyPositionService policyPositionService;

    @Resource
    private BusPolicySalemanService policySalemanService;

    @Resource
    private AppPositionService positionService;

    @Autowired
    private SettleStrategyContext settleStrategyContext;

    /**
     * 设置订单相关结算人员(商务经理，片区服务商，商务总负责人)
     *
     * @param saleman
     * @param hyOrder
     */
    public void setSaleManInfo(HyOrder hyOrder, BusSaleman saleman) {
        if (FlymeUtils.isNotEmpty(saleman)) {
            Long saleManId = saleman.getSaleManId();
            //职务ID
            Long positionId = saleman.getPositionId();
            ApiAssert.isNotEmpty("业务员职务未设置", positionId);
            AppPosition position = positionService.getById(positionId);
            ApiAssert.isNotEmpty("业务员职务不存在", position);
            //职务编码
            String positionNo = position.getPositionNo();
            if (FlymeUtils.isNotEmpty(positionNo)) {
                //渠道商
                if (positionNo.contains("F")) {
                    hyOrder.setSaleManIdF(saleManId);
                }
                //商务经理
                if (positionNo.equals("D")) {
                    hyOrder.setSaleManIdD(saleManId);
                }
                //片区服务商
                if (positionNo.equals("C")) {
                    hyOrder.setSaleManIdC(saleManId);
                }
                //商务总负责人(省级)
                if (positionNo.equals("E")) {
                    hyOrder.setSaleManIdE(saleManId);
                    hyOrder.setProLevel(1);
                    checkSaleManE(hyOrder, saleman);
                }
                Long parentId = saleman.getParentId();
                BusSaleman parent = saleManService.getById(parentId);
                setSaleManInfo(hyOrder, parent);
            }
        }
    }

    /**
     * 校验商务总负责人(根据配置重新设置是否计算商务总负责人结算)
     *
     * @param saleman
     * @param hyOrder
     */
    public void checkSaleManE(HyOrder hyOrder, BusSaleman saleman) {
        //业务员唯一编码
        String saleManCode = FlymeUtils.getString(hyOrder.getSaleManCode(), "");
        //商务负责人唯一编码
        String saleManCodeE = FlymeUtils.getString(saleman.getSaleManCode(), "");
        //是否享受升级结算
        Integer proLeval = FlymeUtils.getInteger(saleman.getProLevel(), 0);
        hyOrder.setProLevel(proLeval);
        if (proLeval.equals(0)) {
            hyOrder.setSaleManIdE(null);
        }
        //自己发货时也不享受商务负责人结算
        if (FlymeUtils.isNotEmpty(saleManCodeE) && saleManCodeE.equals(saleManCode)) {
            hyOrder.setSaleManIdE(null);
        }
    }


    /**
     * 设置结算政策
     */
    private void setSettelPolicy(AppPosition position, BusPolicyDrug policyDrug, HyOrder order, HyOrderDetail orderDetail, BusDept dept) {
        //自定义结算政策
        Integer customPolicy = FlymeUtils.getInteger(orderDetail.getCustomPolicy(), 0);
        //部门结算价
        BigDecimal deptPrice = FlymeUtils.getBigDecimal(orderDetail.getDeptPrice(), new BigDecimal("0"));
        //部门结算标准
        BigDecimal deptRate = FlymeUtils.getBigDecimal(orderDetail.getDeptRate(), new BigDecimal("0"));
        //部门结算公式内容
        String deptSettleFormula = orderDetail.getDeptSettleFormula();
        //部门利润公式
        String deptProfitAmountFormula = orderDetail.getDeptProfitAmountFormula();
        //结算政策ID
        Long policyDrugId = null;
        //发货日期
        Date sendDate = order.getSendDate();
        //职务ID
        Long positionId = order.getPositionId();
        /*********************全局结算政策*******************************/
        if (FlymeUtils.isNotEmpty(policyDrug) && customPolicy.equals(0)) {
            //结算政策ID
            policyDrugId = policyDrug.getPolicyDrugId();
            //部门ID
            Long deptId = dept.getDeptId();
            String deptType = dept.getDeptType();
            BusPolicyDept policyDept = policyDeptService.findByPolicyDrugIdAndDeptId(policyDrugId, deptId, sendDate);
            //只有自营部门计算部门结算
            if (DeptTypeEnum.ZY.getCode().equals(deptType)) {
                //部门结算价
                deptPrice = FlymeUtils.getBigDecimal(policyDrug.getDeptPrice(), "0");
                //部门结算标准
                deptRate = FlymeUtils.getBigDecimal(policyDrug.getDeptRate(), "0");
                //部门结算公式内容
                deptSettleFormula = FlymeUtils.getString(policyDrug.getDeptSettleFormula());
                //部门利润公式
                deptProfitAmountFormula = FlymeUtils.getString(policyDrug.getDeptProfitAmountFormula());
                /*********************部门结算政策*******************************/
                if (FlymeUtils.isNotEmpty(policyDept)) {
                    BigDecimal deptPrice1 = policyDept.getDeptPrice();
                    if (FlymeUtils.isNotEmpty(deptPrice1)) {
                        deptPrice = deptPrice1;
                    }
                    BigDecimal deptRate1 = policyDept.getDeptRate();
                    if (FlymeUtils.isNotEmpty(deptRate1)) {
                        deptRate = deptRate1;
                    }
                    String deptSettleFormula1 = policyDept.getDeptSettleFormula();
                    if (FlymeUtils.isNotEmpty(deptSettleFormula1)) {
                        deptSettleFormula = deptSettleFormula1;
                    }
                }
            }
            //招商品种的部门配置给渠道商
            if (DeptTypeEnum.ZS.getCode().equals(deptType)) {
                if (FlymeUtils.isNotEmpty(policyDept)) {
                    BigDecimal deptRate1 = FlymeUtils.getBigDecimal(policyDept.getDeptRate(), orderDetail.getSettleRate());
                    orderDetail.setSettleRate(deptRate1);
                }
            }
        }
        orderDetail.setDeptPrice(deptPrice);
        orderDetail.setDeptRate(deptRate);
        orderDetail.setDeptSettleFormula(deptSettleFormula);
        orderDetail.setDeptProfitAmountFormula(deptProfitAmountFormula);
        //设置分级结算价格
        settleStrategyContext.setSettleStrategy(position, orderDetail, order);
    }


    /**
     * 计算费用
     *
     * @param hyOrder
     * @param hyOrderDetail
     * @param checkPolicy   是否检测政策(录单时不检测)
     * @param discount      是否是票折
     */
    public void computeFee(HyOrder hyOrder, HyOrderDetail hyOrderDetail, Boolean checkPolicy, Boolean discount) {
        //业务职务ID
        Long positionId = hyOrder.getPositionId();
        //查询业务员职务
        AppPosition position = positionService.getById(positionId);
        //销售数量
        BigDecimal saleNum = new BigDecimal("0");
        //销售价
        BigDecimal salePrice = new BigDecimal("0");
        //成本价
        BigDecimal costPrice = new BigDecimal("0");
        //成本金额
        BigDecimal costAmount = new BigDecimal("0");
        //销售金额
        BigDecimal saleAmount = hyOrderDetail.getSaleAmount();
        //非票折
        if (!discount) {
            saleNum = hyOrderDetail.getSaleNum();
            salePrice = hyOrderDetail.getSalePrice();
            saleAmount = salePrice.multiply(saleNum);
            costPrice = FlymeUtils.getBigDecimal(hyOrderDetail.getCostPrice(), "0");
            //成本金额
            costAmount = costPrice.multiply(saleNum);
        } else {
            saleNum = hyOrderDetail.getSaleNum().multiply(new BigDecimal("-1"));
            salePrice = hyOrderDetail.getSalePrice();
            hyOrderDetail.setSettleFormulaContent("票折金额*(1-渠道商标准);");
        }
        hyOrderDetail.setSaleAmount(saleAmount);
        hyOrderDetail.setSaleNum(saleNum);
        hyOrderDetail.setSalePrice(salePrice);
        hyOrderDetail.setCostPrice(costPrice);
        hyOrderDetail.setCostAmount(costAmount);

        hyOrderDetail.setSettleSendAmount(new BigDecimal("0"));
        hyOrderDetail.setSettleAmount(new BigDecimal("0"));
        hyOrderDetail.setSettleAmountD(new BigDecimal("0"));
        hyOrderDetail.setSettleAmountE(new BigDecimal("0"));
        hyOrderDetail.setSettleAmountC(new BigDecimal("0"));
        hyOrderDetail.setDeptSettleAmount(new BigDecimal("0"));
        hyOrderDetail.setDeptProfitAmount(new BigDecimal("0"));
        if (checkPolicy.equals(0)) {
            hyOrderDetail.setSettleRate(null);
            hyOrderDetail.setSettleRateC(null);
            hyOrderDetail.setSettleRateD(null);
            hyOrderDetail.setSettlePrice(null);
            hyOrderDetail.setSettlePriceD(null);
            hyOrderDetail.setSettlePriceC(null);
            hyOrderDetail.setSettlePriceE(null);
            hyOrderDetail.setSettleRateE(new BigDecimal("0"));
            hyOrderDetail.setDeptRate(new BigDecimal("0"));
            hyOrderDetail.setDeptPrice(new BigDecimal("0"));
            hyOrderDetail.setDeptProfitAmountFormula(null);
            hyOrderDetail.setSettleFormulaContent(null);
            hyOrderDetail.setSettleFormulaContentC(null);
            hyOrderDetail.setSettleFormulaContent(null);
            hyOrderDetail.setSettleFormulaContentE(null);
        }
        //部门
        BusDept dept = deptService.getById(hyOrder.getDeptId());
        if (FlymeUtils.isNotEmpty(dept)) {
            //默认部门结算税率
            BigDecimal deptSettleRate = FlymeUtils.getBigDecimal(dept.getSettleRate(), "0.185");
            //部门类型
            String deptType = dept.getDeptType();
            //招商类型的渠道商结算价就是成本价
            if (FlymeUtils.isNotEmpty(deptType)) {
                if (deptType.equals("ZS")) {
                    //招商品种的渠道商结算价取成本价
                    hyOrderDetail.setSettlePrice(hyOrderDetail.getCostPrice());
                    hyOrderDetail.setSettleRate(deptSettleRate);
                }
            }
            //商品编号
            String drugNo = hyOrderDetail.getDrugNo();
            Long companyId = hyOrder.getCompanyId();
            BusDrugs busDrugs = drugsService.selectByDrugNo(drugNo, companyId);
            if (checkPolicy) {
                ApiAssert.isNotEmpty("商品未同步", busDrugs);
            }
            //根据商品名称和规格查询结算政策
            if (FlymeUtils.isNotEmpty(busDrugs)) {
                Long policyDrugId = busDrugs.getPolicyDrugId();
                if (checkPolicy) {
                    ApiAssert.isNotEmpty("结算政策未设置", policyDrugId);
                }
                BusPolicyDrug policyDrug = policyDrugService.getById(policyDrugId);
                if (checkPolicy) {
                    ApiAssert.isNotEmpty("结算政策不存在", policyDrug);
                }
                if (FlymeUtils.isNotEmpty(policyDrug)) {
                    //底价方式
                    Integer floorPriceType = FlymeUtils.getInteger(policyDrug.getFloorPriceType(), 1);
                    hyOrderDetail.setFloorPriceType(floorPriceType);
                    //结算政策ID
                    hyOrderDetail.setPolicyDrugId(policyDrug.getPolicyDrugId());
                    //设置结算政策
                    setSettelPolicy(position, policyDrug, hyOrder, hyOrderDetail, dept);
                }
                //如果部门类型为空则取商品类型
                if (FlymeUtils.isEmpty(deptType)) {
                    deptType = busDrugs.getDrugType();
                }
            }
            /***************************计算结算费用************************************/
            //获取公式计算元素
            Map<String, Object> variable = getVariable(hyOrderDetail);
            //计算结算金额
            settleStrategyContext.setSettleAmount(position, hyOrderDetail, hyOrder, variable);
            //市场结算价
            BigDecimal settlePrice = FlymeUtils.getBigDecimal(getSettlePrice(hyOrderDetail), "0");
            //市场结算标准
            BigDecimal settleRate = FlymeUtils.getBigDecimal(getSettleRate(hyOrderDetail), "0");
            /**************************底价和税金计算**************************************/
            //资保金金应收金额
            BigDecimal customBond = new BigDecimal("0");
            //发货方式
            Integer sendType = hyOrder.getSendType();
            //资信发货
            if (SendTypeEnum.ZBJ.getCode().equals(sendType)) {
                //底价
                BigDecimal customFloorAmount = new BigDecimal("0");
                //底价方式(1按结算价 2按成本价)
                Integer floorPrice = FlymeUtils.getInteger(hyOrderDetail.getFloorPriceType(), 2);
                //招商部门底价按成本价计算
                if (floorPrice.equals(CommonConstants.INT_1) && DeptTypeEnum.ZY.getCode().equals(deptType)) {
                    //结算价*数量
                    customFloorAmount = settlePrice.multiply(saleNum);
                } else {
                    //成本价*数量
                    customFloorAmount = costPrice.multiply(saleNum);
                }
                //底价公式
                String customFloorAmountFormula = hyOrderDetail.getCustomFloorAmountFormula();
                if (FlymeUtils.isNotEmpty(customFloorAmountFormula)) {
                    customFloorAmount = groovyScriptEngine.executeBigDecimal(customFloorAmountFormula, variable, 2);
                }
                hyOrderDetail.setCustomFloorAmount(customFloorAmount);
                //高开金额
                BigDecimal multiply = (salePrice.subtract(settlePrice)).multiply(saleNum);
                //高开税金(销售单价-市场结算价)*数量*(市场结算标准)
                BigDecimal customGapUpAmount = multiply.multiply(settleRate);
                //票折
                if (discount) {
                    customGapUpAmount = saleAmount.multiply(settleRate);
                }
                hyOrderDetail.setCustomGapUpAmount(customGapUpAmount);
                //资信方式
                Integer customBondType = hyOrder.getCustomBondType();
                //底价
                if (customBondType.equals(CommonConstants.INT_1)) {
                    customBond = customFloorAmount;
                }
                //高开税金
                if (customBondType.equals(CommonConstants.INT_2)) {
                    customBond = customGapUpAmount;
                }
                //底价+高开税金
                if (customBondType.equals(CommonConstants.INT_3)) {
                    customBond = customFloorAmount.add(customGapUpAmount);
                }
                //全款
                if (customBondType.equals(4)) {
                    customBond = saleAmount;
                }
                log.info("################################资保金金额计算#############################################");
                log.info("##########################资保金金额:{}", customBond);
                log.info("##########################底价:{}", customFloorAmount);
                log.info("##########################税金:{}", customGapUpAmount);
                log.info("##########################成本价:{}", hyOrderDetail.getCostPrice());
                log.info("##########################标准:{}", hyOrderDetail.getSettleRate());
                //未退款
                hyOrderDetail.setCustomBondState(CommonConstants.INT_0);
                //ApiAssert.gtzero("资保金金额不正确", customBond);
            }
            hyOrderDetail.setCustomBond(customBond);
            //部门结算价
            BigDecimal deptPrice = FlymeUtils.getBigDecimal(hyOrderDetail.getDeptPrice(), "0");
            //部门结算税率
            BigDecimal deptRate = FlymeUtils.getBigDecimal(hyOrderDetail.getDeptRate(), "0");
            BigDecimal deptSettleAmount = new BigDecimal("0");
            BigDecimal deptProfitAmount = new BigDecimal("0");
            //判断是否计算税率差
            Boolean computeTaxRateDiff = computeTaxRateDiff(hyOrder, hyOrderDetail);
            BigDecimal taxRateDiff = new BigDecimal("0");
            if (computeTaxRateDiff) {
                /**************************税率差**************************************/
                String taxRateDiffFormula = hyOrderDetail.getTaxRateDiffFormula();
                if (FlymeUtils.isNotEmpty(taxRateDiffFormula)) {
                    taxRateDiff = groovyScriptEngine.executeBigDecimal(taxRateDiffFormula, variable, 2);
                }
            }
            hyOrderDetail.setTaxRateDiff(taxRateDiff);
            variable.put("超标准差额", taxRateDiff);
            /**************************部门结算金额（自营品类计算）**************************************/
            if (deptType.equals(DeptTypeEnum.ZY.getCode())) {
                //默认部门结算金额(含税单价-部门结算价)*数量*(1-部门结算标准)
                deptSettleAmount = (salePrice.subtract(deptPrice)).multiply(saleNum).multiply(new BigDecimal("1").subtract(deptRate));
                //部门结算金额公式
                String deptSettleFormula = hyOrderDetail.getDeptSettleFormula();
                if (discount) {
                    deptSettleFormula = ("票折金额*(1-部门标准);");
                    hyOrderDetail.setDeptSettleFormula(deptSettleFormula);
                }
                //使用公式重新计算部门结算金额
                if (FlymeUtils.isNotEmpty(deptSettleFormula)) {
                    deptSettleAmount = groovyScriptEngine.executeBigDecimal(deptSettleFormula, variable, 2);
                }
                variable.put("部门费用", deptSettleAmount);
                /**************************部门利润**************************************/
                //部门利润公式
                String deptProfitAmountFormula = hyOrderDetail.getDeptProfitAmountFormula();
                //使用公式重新计算部门利润公式
                if (FlymeUtils.isNotEmpty(deptProfitAmountFormula)) {
                    deptProfitAmount = groovyScriptEngine.executeBigDecimal(deptProfitAmountFormula, variable, 2);
                }
                hyOrderDetail.setDeptProfitAmount(deptProfitAmount);
            }
            hyOrderDetail.setDeptSettleAmount(deptSettleAmount);
            variable.put("部门利润", deptProfitAmount);
            /**************************支付开票税金=部门结算金额*1.3226%**************************************/
            BigDecimal payInvoiceTaxAmount = deptSettleAmount.multiply(new BigDecimal("0.013226")).setScale(2, BigDecimal.ROUND_HALF_UP);
            hyOrderDetail.setPayInvoiceTaxAmount(payInvoiceTaxAmount);
            variable.put("支付开票税金", payInvoiceTaxAmount);
            BigDecimal profitAmount1 = saleAmount.subtract(costAmount);

            BigDecimal profitAmount0 = profitAmount1.divide(new BigDecimal("1.13"), 4, BigDecimal.ROUND_HALF_UP);
            /**************************税收利润=(销售金额-成本金额)/1.13*0.13*0.45**************************************/
            BigDecimal taxProfitAmount = profitAmount0.multiply(new BigDecimal("0.13")).multiply(new BigDecimal("0.45")).setScale(2, BigDecimal.ROUND_HALF_UP);
            hyOrderDetail.setTaxProfitAmount(taxProfitAmount);
            variable.put("税收利润", payInvoiceTaxAmount);

            /**************************产品利润=(部门结算价-成本价)*数量-(部门结算价-成本价)*数量/1.13*0.13*1.12**************************************/
            BigDecimal amount1 = (deptPrice.subtract(costPrice)).multiply(saleNum);
            if (DeptTypeEnum.ZS.getCode().equals(deptType)) {
                //产品利润=(渠道商结算价-成本价)*数量-(渠道商结算价-成本价)*数量/1.13*0.13*1.12
                amount1 = (settlePrice.subtract(costPrice)).multiply(saleNum);
            }
            BigDecimal amount2 = ((amount1.divide(new BigDecimal("1.13"), 4, BigDecimal.ROUND_HALF_UP)).multiply(new BigDecimal("0.13")).multiply(new BigDecimal("1.12"))).setScale(2, BigDecimal.ROUND_HALF_UP);
            BigDecimal drugProfitAmount = amount1.subtract(amount2);
            hyOrderDetail.setDrugProfitAmount(drugProfitAmount);
            variable.put("产品利润", drugProfitAmount);
            /**************************边际利润=(含税单价-部门结算价)*数量-(含税单价-部门结算价)*数量/1.13*0.13*1.12-部门结算费用-支付开票税金;**************************************/
            BigDecimal amount3 = (salePrice.subtract(deptPrice)).multiply(saleNum);
            if (DeptTypeEnum.ZS.getCode().equals(deptType)) {
                amount3 = (salePrice.subtract(settlePrice)).multiply(saleNum);
            }
            BigDecimal amount4 = ((amount3.divide(new BigDecimal("1.13"), 4, BigDecimal.ROUND_HALF_UP)).multiply(new BigDecimal(0.13)).multiply(new BigDecimal("1.12"))).setScale(2, BigDecimal.ROUND_HALF_UP);
            BigDecimal bjProfitAmount = amount3.subtract(amount4).subtract(deptSettleAmount).subtract(payInvoiceTaxAmount);
            //票折边际利润 (发货金额-成本金额)-(发货金额-成本金额)/1.13*0.13*1.12-部门结算费用-支付开票税金;
            if (discount) {
                bjProfitAmount = amount3.subtract(amount4).subtract(deptSettleAmount).subtract(payInvoiceTaxAmount);
            }
            variable.put("边际利润", bjProfitAmount);
            hyOrderDetail.setBjProfitAmount(bjProfitAmount);
            /**************************公司利润**************************************/
            BigDecimal profitAmount2 = (profitAmount0.multiply(new BigDecimal("0.13")).multiply(new BigDecimal("1.12"))).setScale(2, BigDecimal.ROUND_HALF_UP);
            BigDecimal profitAmount = profitAmount1.subtract(profitAmount2).subtract(deptSettleAmount).subtract(payInvoiceTaxAmount);
            if (DeptTypeEnum.ZS.getCode().equals(deptType)) {
                BigDecimal settleAmount = FlymeUtils.getBigDecimal(hyOrderDetail.getSettleAmount(), "0");
                profitAmount = profitAmount1.subtract(profitAmount2).subtract(settleAmount).subtract(payInvoiceTaxAmount);
            }
            String profitAmountFormula = hyOrderDetail.getProfitAmountFormulaContent();
            if (FlymeUtils.isNotEmpty(profitAmountFormula)) {
                profitAmount = groovyScriptEngine.executeBigDecimal(profitAmountFormula, variable, 2);
            }
            hyOrderDetail.setProfitAmount(profitAmount);
            /**************************校验=公司利润-产品利润-边际利润**************************************/
            BigDecimal checkAmount = profitAmount.subtract(drugProfitAmount).subtract(bjProfitAmount);
            hyOrderDetail.setCheckAmount(checkAmount);
        }
    }

    /**
     * 设置公式计算元素
     *
     * @return
     */
    public Map<String, Object> getVariable(HyOrderDetail orderDetail) {
        String saleType = orderDetail.getSaleType();
        Map<String, Object> variable = new HashMap<>(5);
        variable.put("数量", orderDetail.getSaleNum());
        variable.put("销售单价", orderDetail.getSalePrice());
        variable.put("开票价", orderDetail.getSalePrice());
        variable.put("含税单价", orderDetail.getSalePrice());
        variable.put("提成单价", orderDetail.getRebateAmount());
        variable.put("成本价", orderDetail.getCostPrice());
        variable.put("最高加价", orderDetail.getMakeUpPriceD());
        variable.put("无税单价", orderDetail.getCostPrice());
        variable.put("渠道商结算价", FlymeUtils.getBigDecimal(orderDetail.getSettlePrice(), "0"));
        variable.put("渠道商标准", FlymeUtils.getBigDecimal(orderDetail.getSettleRate(), "0"));
        variable.put("商务经理结算价", FlymeUtils.getBigDecimal(orderDetail.getSettlePriceD(), "0"));
        variable.put("商务经理标准", FlymeUtils.getBigDecimal(orderDetail.getSettleRateD(), "0"));
        variable.put("片区服务商结算价", FlymeUtils.getBigDecimal(orderDetail.getSettlePriceC(), "0"));
        variable.put("片区服务商标准", FlymeUtils.getBigDecimal(orderDetail.getSettleRateC(), "0"));
        variable.put("商务总负责人结算价", FlymeUtils.getBigDecimal(orderDetail.getSettlePriceE(), "0"));
        variable.put("商务总负责人标准", FlymeUtils.getBigDecimal(orderDetail.getSettleRateE(), "0"));
        variable.put("部门结算价", FlymeUtils.getBigDecimal(orderDetail.getDeptPrice(), "0"));
        variable.put("部门标准", FlymeUtils.getBigDecimal(orderDetail.getDeptRate(), "0"));
        if (HySaleTypeEnum.Pz.getCode().equals(saleType)) {
            variable.put("票折金额", FlymeUtils.getBigDecimal(orderDetail.getSaleAmount(), "0"));
        }
        //初始值
        variable.put("渠道商结算金额", new BigDecimal("0"));
        variable.put("商务经理结算金额", new BigDecimal("0"));
        variable.put("片区服务商结算金额", new BigDecimal("0"));
        variable.put("商务总负责人结算金额", new BigDecimal("0"));
        return variable;
    }


    /**
     * 获取人员区域ID
     *
     * @param saleman
     * @return
     */
    public Long getAreaId(BusSaleman saleman) {
        Long areaId = saleman.getAreaId();
        if (FlymeUtils.isNotEmpty(areaId)) {
            return areaId;
        }
        Long cityId = saleman.getCityId();
        if (FlymeUtils.isNotEmpty(cityId)) {
            return cityId;
        }
        Long proId = saleman.getProId();
        if (FlymeUtils.isNotEmpty(proId)) {
            return proId;
        }
        return null;
    }

    /**
     * 获取市场结算价
     *
     * @param hyOrderDetail
     * @return
     */
    private BigDecimal getSettlePrice(HyOrderDetail hyOrderDetail) {
        Long saleManId = hyOrderDetail.getSaleManId();
        Long saleManIdC = hyOrderDetail.getSaleManIdC();
        Long saleManIdD = hyOrderDetail.getSaleManIdD();
        Long saleManIdE = hyOrderDetail.getSaleManIdE();
        BigDecimal settlePriceF = hyOrderDetail.getSettlePrice();
        BigDecimal settlePriceD = hyOrderDetail.getSettlePriceD();
        BigDecimal settlePriceC = hyOrderDetail.getSettlePriceC();
        BigDecimal settlePriceE = hyOrderDetail.getSettlePriceE();
        //跟业务员是同一个人
        if (FlymeUtils.isNotEmpty(settlePriceE) && FlymeUtils.gtzero(settlePriceE) && saleManId.equals(saleManIdE)) {
            return settlePriceE;
        }
        if (FlymeUtils.isNotEmpty(settlePriceC) && FlymeUtils.gtzero(settlePriceC) && saleManId.equals(saleManIdC)) {
            return settlePriceC;
        }
        if (FlymeUtils.isNotEmpty(settlePriceD) && FlymeUtils.gtzero(settlePriceD) && saleManId.equals(saleManIdD)) {
            return settlePriceD;
        }
        return settlePriceF;
    }

    /**
     * 获取市场结算标准
     *
     * @param hyOrderDetail
     * @return
     */
    private BigDecimal getSettleRate(HyOrderDetail hyOrderDetail) {
        Long saleManId = hyOrderDetail.getSaleManId();
        Long saleManIdC = hyOrderDetail.getSaleManIdC();
        Long saleManIdD = hyOrderDetail.getSaleManIdD();
        Long saleManIdE = hyOrderDetail.getSaleManIdE();
        BigDecimal settleRateF = hyOrderDetail.getSettleRate();
        BigDecimal settleRateD = hyOrderDetail.getSettleRateD();
        BigDecimal settleRateC = hyOrderDetail.getSettleRateC();
        BigDecimal settleRateE = hyOrderDetail.getSettleRateE();
        if (FlymeUtils.isNotEmpty(settleRateE) && FlymeUtils.gtzero(settleRateE) && saleManId.equals(saleManIdE)) {
            return settleRateE;
        }
        if (FlymeUtils.isNotEmpty(settleRateC) && FlymeUtils.gtzero(settleRateC) && saleManId.equals(saleManIdC)) {
            return settleRateC;
        }
        if (FlymeUtils.isNotEmpty(settleRateD) && FlymeUtils.gtzero(settleRateD) && saleManId.equals(saleManIdD)) {
            return settleRateD;
        }
        return settleRateF;
    }

    /**
     * 判断是否计算税率差
     *
     * @return
     */
    private Boolean computeTaxRateDiff(HyOrder order, HyOrderDetail orderDetail) {
        Boolean result = true;
        //部门税率
        BigDecimal deptRate = FlymeUtils.getBigDecimal(orderDetail.getDeptRate(), "0");
        //商务负责人税率
        BigDecimal settleRateE = orderDetail.getSettleRateE();
        //片区服务商税率
        BigDecimal settleRateC = orderDetail.getSettleRateC();
        //商务经理税率
        BigDecimal settleRateD = orderDetail.getSettleRateD();
        //当商务负责人 片区服务商 商务经理任何一方税率和部门相同时都不计算税率差
        if (FlymeUtils.isNotEmpty(settleRateE) && settleRateE.equals(deptRate)) {
            result = false;
        }

        if (FlymeUtils.isNotEmpty(settleRateC) && settleRateC.equals(deptRate)) {
            result = false;
        }

        if (FlymeUtils.isNotEmpty(settleRateD) && settleRateD.equals(deptRate)) {
            result = false;
        }
        //settleAmountType=2时为佣金制不计算税率差
        Integer settleAmountType = FlymeUtils.getInteger(orderDetail.getSettleAmountType(), 1);
        if (settleAmountType.equals(2)) {
            result = false;
        }
        return result;
    }

    /**
     * 按比例计算金额
     *
     * @param ratio         拆分比例
     * @param computeAmount 当前需要计算的字段金额
     * @return
     */
    public BigDecimal computeAmount(BigDecimal ratio, BigDecimal computeAmount) {
        if (FlymeUtils.isNotEmpty(computeAmount) && FlymeUtils.nezero(computeAmount)) {
            return (computeAmount.multiply(ratio)).setScale(2, BigDecimal.ROUND_HALF_UP);
        }
        return new BigDecimal("0");
    }

}
